package com.netease.neliveplayer.playerkit.videoLoader;

import android.util.Log;
import android.widget.ProgressBar;

import androidx.annotation.CallSuper;
import androidx.annotation.Px;
import androidx.viewpager2.widget.ViewPager2;

import com.netease.neliveplayer.playerkit.common.log.LogUtil;
import com.netease.neliveplayer.playerkit.sdk.view.AdvanceTextureView;

import java.util.ArrayList;
import java.util.Arrays;

abstract public class OnVideoItemScrollEventHandler extends ViewPager2.OnPageChangeCallback {
    private int POSITION_NONE = -1;
    private int currLoadPosition = POSITION_NONE;
    private int preLoadPosition = POSITION_NONE;
    private int scrollStatus = ViewPager2.SCROLL_STATE_IDLE;
    private float PRE_LOAD_OFFSET = 0.001f;
    private float lastOffset = 0f;
    private  ArrayList<VideoLoader.VideoInfo> videoList = new ArrayList<>();
    public static boolean needRenderLater;
    private ArrayList<String> urlLoadLater;
    private ViewPager2 mViewPager;
    private static boolean needStartLoading;
    public static boolean needRefreshProgressBar = true;
    public OnVideoItemScrollEventHandler(ViewPager2 ViewPager){
        mViewPager = ViewPager;
    }

    @Override
    @CallSuper
    public void onPageScrollStateChanged(int state) {
        LogUtil.info( "[scrollEvent]onPageScrollStateChanged");
        switch (state) {
            case ViewPager2.SCROLL_STATE_IDLE:
                if(preLoadPosition != POSITION_NONE){
                    //preLoadPosition 页面消失
                    pageLeft(preLoadPosition);
                    LogUtil.info( "[scrollEvent]onPageScrollStateChanged preLoadPosition");
                }
                LogUtil.info( "[scrollEvent]needStartLoading: "+ needStartLoading + " preLoadPosition: " + preLoadPosition);
                if(needStartLoading && VideoLoaderImpl.getInstance().getMode() == 0){
                    needStartLoading = false;
                    pageStartLoading(currLoadPosition);
                }
                //currLoadPosition 页面显示完成
                pageLoaded(currLoadPosition);
                preLoadPosition = POSITION_NONE;
                lastOffset = 0f;
                LogUtil.info( "[scrollEvent] pageLoaded:" + currLoadPosition);
                if(mViewPager != null)
                    mViewPager.setUserInputEnabled(true);
                break;
            case ViewPager2.SCROLL_STATE_DRAGGING:
                //滑动
                break;
            case ViewPager2.SCROLL_STATE_SETTLING:
                //松手
                if(mViewPager != null)
                    mViewPager.setUserInputEnabled(false);
                break;
        }
        scrollStatus = state;
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels);
        if(scrollStatus == ViewPager2.SCROLL_STATE_DRAGGING){
            needStartLoading = true;
            if(lastOffset > 0f) {
                needStartLoading = false;
                boolean isScrollUp = (positionOffset - lastOffset) > 0;
                if(isScrollUp && positionOffset >= PRE_LOAD_OFFSET && preLoadPosition == POSITION_NONE){
                    preLoadPosition = currLoadPosition + 1;
                    pageStartLoading(preLoadPosition);
                }else if(!isScrollUp && positionOffset <= (1 - PRE_LOAD_OFFSET) && preLoadPosition == POSITION_NONE){
                    preLoadPosition = currLoadPosition - 1;
                    pageStartLoading(preLoadPosition);
                }
            }
            lastOffset = positionOffset;
        }
    }
    @Override
    public void onPageSelected(int position) {
        super.onPageSelected(position);
        if(currLoadPosition != POSITION_NONE){
            if(preLoadPosition != POSITION_NONE){
                if(position == preLoadPosition){
                    //currLoadPosition页面消失
                    pageLeft(currLoadPosition);
                    LogUtil.info( "[scrollEvent]onPageSelected currLoadPosition页面消失");
                }else{
                    //preLoadPosition页面消失
                    pageLeft(preLoadPosition);
                    LogUtil.info( "[scrollEvent]onPageSelected preLoadPosition页面消失");

                    //position页面准备显示
                    pageStartLoading(position);
                    LogUtil.info( "[scrollEvent]onPageSelected currLoadPosition页面显示完成");
                }
            }
        }
        currLoadPosition = position;
        preLoadPosition = POSITION_NONE;
        lastOffset = 0f;
    }
    public void pageLeft(int position){
        onPageLeft(position);
    }

    public void pageLoaded(int position){
        VideoLoader.VideoInfo info = videoList.get(position % videoList.size());
        VideoLoader.VideoInfo linfo = videoList.get(Math.max(0, (position - 1)) % videoList.size());
        VideoLoader.VideoInfo ninfo = videoList.get((position + 1) % videoList.size());
        VideoLoader.VideoInfo nninfo = videoList.get((position + 2) % videoList.size());

        AdvanceTextureView view = onRequireRenderVideo(position);
        ProgressBar progressBar = onRequireSeekBar(position);
        needRenderLater = view == null;
        if (needRenderLater) {
            urlLoadLater = info.url;
            return;
        }
        VideoLoaderImpl.getInstance().registerPlayerListener(new PlayerListener() {
            @Override
            public void onError(int what, int extra) {

            }

            @Override
            public void onCurrentPlayProgress(long currentPosition, long duration, float percent, long cachedPosition) {
                if(needRefreshProgressBar)
                    progressBar.setProgress((int)percent);
            }
        });
        if(VideoLoaderImpl.getInstance().getMode() == 1) {
            VideoLoaderImpl.getInstance().renderAndPlay(info.url, view);
        }else if(VideoLoaderImpl.getInstance().getMode() == 0) {
            VideoLoaderImpl.getInstance().playAndUnmute(info.url, view);
        }
        onPageLoaded(position);
        ArrayList<ArrayList<String>> urlList = new ArrayList<>(Arrays.asList(info.url, linfo.url, ninfo.url, nninfo.url));
        VideoLoaderImpl.getInstance().setLivePlayerURLList(urlList);
        //打开所有定时器
        VideoLoaderImpl.getInstance().startAllRefresher();
    }

    /**
     * 当用户开始滑动的时候要进行播放器的预加载
     * @param position
     */
    public void pageStartLoading(int position){
        //停止所有定时器
        VideoLoaderImpl.getInstance().stopAllRefresher();
        if(VideoLoaderImpl.getInstance().getMode() == 0) {
            VideoLoader.VideoInfo info = videoList.get((position) % videoList.size());
            AdvanceTextureView view = onRequireRenderVideo(position);
            ProgressBar progressBar = onRequireSeekBar(position);
            needRenderLater = view == null;
            if (needRenderLater) {
                urlLoadLater = info.url;
                return;
            }
            VideoLoaderImpl.getInstance().registerPlayerListener(new PlayerListener() {
                @Override
                public void onError(int what, int extra) {

                }

                @Override
                public void onCurrentPlayProgress(long currentPosition, long duration, float percent, long cachedPosition) {
                    if(needRefreshProgressBar)
                        progressBar.setProgress((int)percent);
                }
            });
            VideoLoaderImpl.getInstance().renderAndMute(info.url, view);
        }
        onPageStartLoading(position);
    }
    abstract public void onPageStartLoading(int position);

    abstract public void onPageLoaded(int position);

    abstract public void onPageLeft(int position);

    abstract public AdvanceTextureView onRequireRenderVideo(int position);

    abstract public ProgressBar onRequireSeekBar(int position);

    public void updateVideoList(ArrayList<VideoLoader.VideoInfo> list){
        videoList = list;
    }

    /**
     * fragment创建调用
     * 需要在fragment的onCreateView结束时调用
     * @param canvas
     */
    public void onCreateView(AdvanceTextureView canvas, ProgressBar progressBar){
        if(needRenderLater){
            LogUtil.info( "[scrollEvent] onCreateView");
            VideoLoaderImpl.getInstance().registerPlayerListener(new PlayerListener() {
                @Override
                public void onError(int what, int extra) {
                }

                @Override
                public void onCurrentPlayProgress(long currentPosition, long duration, float percent, long cachedPosition) {
                    if(needRefreshProgressBar)
                        progressBar.setProgress((int)percent);
                }
            });
            VideoLoaderImpl.getInstance().stopAllRefresher();
            needRenderLater = false;
            VideoLoaderImpl.getInstance().renderAndPlay(urlLoadLater, canvas);
            VideoLoaderImpl.getInstance().startAllRefresher();
            VideoLoaderImpl.getInstance().setScrollMode(true);

        }
    }
    public void onVideoCreated(int position) {
        Log.d("qweqwe", "onVideoCreated position:" + position);
        if(position == currLoadPosition) {
            VideoLoaderImpl.getInstance().stopAllRefresher();
            VideoLoader.VideoInfo info = videoList.get(position % videoList.size());

            VideoLoader.VideoInfo linfo = videoList.get(Math.max(0, (position - 1)) % videoList.size());
            VideoLoader.VideoInfo ninfo = videoList.get((position + 1) % videoList.size());
            VideoLoader.VideoInfo nninfo = videoList.get((position + 2) % videoList.size());
            ArrayList<ArrayList<String>> urlList = new ArrayList<>(Arrays.asList(info.url, linfo.url, ninfo.url, nninfo.url));
            VideoLoaderImpl.getInstance().setLivePlayerURLList(urlList);
            
            AdvanceTextureView view = onRequireRenderVideo(position);
            ProgressBar progressBar = onRequireSeekBar(position);
            needRenderLater = view == null;
            if (needRenderLater) {
                urlLoadLater = info.url;
                return;
            }
            VideoLoaderImpl.getInstance().registerPlayerListener(new PlayerListener() {
                @Override
                public void onError(int what, int extra) {
                }

                @Override
                public void onCurrentPlayProgress(long currentPosition, long duration, float percent, long cachedPosition) {
                    if(needRefreshProgressBar)
                        progressBar.setProgress((int)percent);
                }
            });
            LogUtil.info( "[scrollEvent] OnviewCreated");
            VideoLoaderImpl.getInstance().renderAndPlay(info.url, view);
            VideoLoaderImpl.getInstance().startAllRefresher();
        }
    }
}
